package com.common.www.controller.programme;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.common.www.aop.resolver.CurrentUser;
import org.springframework.boot.base.jpa.service.IBaseService;
import com.common.www.bean.entity.Result;
import com.common.www.bean.entity.programme.BasisDemand;
import com.common.www.bean.entity.programme.BasisDemandDetails;
import com.common.www.bean.entity.project.BiddingCompany;
import com.common.www.bean.entity.project.GdyBasic;
import com.common.www.bean.entity.project.SupplyCompany;
import com.common.www.bean.entity.tabulation.InnerBidBaseTabulation;
import com.common.www.bean.entity.tabulation.InnerTabulation;
import com.common.www.bean.vo.UserVo;
import com.common.www.controller.base.DefaultCrudController;
import com.common.www.data.NetCode;
import com.common.www.service.auth.UserService;
import com.common.www.service.programme.BasisDemandDetailsService;
import com.common.www.service.programme.BasisDemandService;
import com.common.www.service.project.GdyBasicService;
import com.common.www.service.project.ProjectService;
import com.common.www.service.project.BiddingCompanyService;
import com.common.www.service.tabulation.InnerBidBaseTabulationService;
import com.common.www.service.tabulation.InnerTabulationService;
import com.common.www.utils.ParamsUtils;
import com.common.www.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@CrossOrigin
@RestController
@RequestMapping(value = {"mgt/basisDemand"})
@Api(tags = "MGT 方案管理接口")
public class BasisDemandController extends DefaultCrudController<BasisDemand, Long> {
    @Autowired
    private BasisDemandService service;
    @Autowired
    private BasisDemandDetailsService basisDemandDetailsService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private BiddingCompanyService biddingCompanyService;
    @Autowired
    private InnerBidBaseTabulationService innerBidBaseTabulationService;
    @Autowired
    private InnerTabulationService innerTabulationService;
    @Autowired
    private GdyBasicService gdyBasicService;
    @Autowired
    private UserService userService;

    protected IBaseService getService() {
        return service;
    }


    @ApiOperation("编辑用需信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "json", value = "String", defaultValue = ""),
    })
    @RequestMapping(value = "/saveByJson", method = RequestMethod.POST)
    public Result saveByJson(String json) {
        BasisDemand item = JSON.parseObject(json, BasisDemand.class);
        BasisDemandDetails itemDetails = item.getDemandDetails();

        if (item.getId() == null) {
            service.saveAndFlush(item);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            BasisDemand existingProject = service.getByIdLogic(item.getId());
            if (existingProject != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(item, existingProject, "id");
                // 然后保存更新后的对象
                service.saveAndFlush(existingProject);
            } else {
                // 如果不存在，则保存解析出来的对象
                service.saveAndFlush(item);
            }
        }
        //保存清单用需详细信息
        if (itemDetails != null && itemDetails.getId() == null) {
            itemDetails.setBasisDemand(item);
            BasisDemandDetails details = basisDemandDetailsService.calculateDetails(itemDetails, item.getProject());
            basisDemandDetailsService.saveAndFlush(details);
        } else {
            // 如果 id 不为空，则从数据库中获取现有对象
            BasisDemandDetails existing = basisDemandDetailsService.getByIdLogic(itemDetails.getId());
            if (existing != null) {
                // 如果存在，则更新现有对象的属性
                BeanUtils.copyProperties(itemDetails, existing, "id");
                // 然后保存更新后的对象
                BasisDemandDetails details = basisDemandDetailsService.calculateDetails(existing, item.getProject());
                basisDemandDetailsService.saveAndFlush(details);
            } else {
                // 如果不存在，则保存解析出来的对象
                BasisDemandDetails details = basisDemandDetailsService.calculateDetails(itemDetails, item.getProject());
                basisDemandDetailsService.saveAndFlush(details);
            }
        }
        return R.ok(itemDetails);
    }


    @ApiOperation("批量删除启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "String", defaultValue = ""),
            @ApiImplicitParam(name = "operate", value = "1.删除 2.启用", defaultValue = ""),
    })
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    public Result batchDelete(Long[] ids, Integer operate) {
        if (ParamsUtils.isInputEmpty(ids, operate)) {
            return R.returnCode(NetCode.CODE_INPUT_OMIT);
        }
        for (int i = 0; i < ids.length; i++) {
            BasisDemand item = service.findOne(ids[i]);
            if (item != null) {
                item.setFlag(0);
                service.save(item);
            }
        }
        return R.ok();
    }


    @ApiOperation(value = "查询用需列表数据", nickname = "", notes = "")
    @ApiImplicitParams(value = {
    })
    @RequestMapping(value = "/query2", produces = {"application/json"}, method = RequestMethod.POST)
    public Result query2(String params, Integer page, Integer size, String sortJsonStr,@CurrentUser UserVo userVo) {
        LinkedHashMap<String, Object> hashMap = (LinkedHashMap<String, Object>)
                JSON.parseObject(params, new TypeReference<LinkedHashMap<String, Object>>() {
                });
        if (hashMap == null) hashMap = new LinkedHashMap<>();
        hashMap.put("flag",1);
        hashMap.put("project.flag",1);
        //拥有权限的任何人可看
        if (!userVo.getAccessList().contains("superManager") && !userVo.getAccessList().contains("高低压配电")) {
            hashMap.put("id", 0);
        }

//        if(!userVo.getAccessList().contains("superManager")){//如果并非是管理员  动态修改权限后  需要重新登录才生效
//            AuthUser authUser = userService.getById(userVo.getId());
//            if(userVo.getAccessList().contains("高低压配电")){
//                if(!StringUtils.isBlank(authUser.getProjectIds())){//新建用户为空的情况
//                    hashMap.put("id_in", FormatUtils.getFormatList(authUser.getProjectIds(), ","));
//                }
//            }else{
//                hashMap.put("id", 0);
//            }
//        }
        Result<List<BasisDemand>> result = this.query(JSONObject.toJSONString(hashMap),  page,  size, sortJsonStr);
//        Result<List<BasisDemand>> result = super.query(params, page, size, sortJsonStr);
        List<BasisDemand> list = result.getData();

        for (BasisDemand basisDemand : list) {
            //高低压配置
            GdyBasic gdyBasic = gdyBasicService.getRepository().findByFlagAndProjectId(1,basisDemand.getProject().getId());
            basisDemand.setGdyBasic(gdyBasic);
            //查询项目对应供应商
            List<BiddingCompany> biddingCompanyList = biddingCompanyService.getRepository().findByFlagAndProjectIdAndInnerOuterTypeAndBidStatus(1, basisDemand.getProject().getId(), 1, 1);
            List<Long> ids = new ArrayList<>();
            for (BiddingCompany company : biddingCompanyList) {
                ids.add(company.getId());
            }

            //数据准备
            int jieDuan = 0;
            int ssdbInnerMark = 0;
            int dbInnerMark = 0;
            SupplyCompany ssdbSupplyCompany = null;
            SupplyCompany dbSupplyCompany = null;

            //查询对应项目内线进行到的最新的阶段(1.标底 6.定标 7.实施标底 8.实施定标),确定出绑定了清单且剩下的供应商
            List<InnerTabulation> ssdbInnerTabulations = new ArrayList<>();
            List<InnerTabulation> dbInnerTabulations = new ArrayList<>();
            if (ids.size() > 0) {
                ssdbInnerTabulations = innerTabulationService.getRepository().getBiddingCompanyIdAndJieDuan(ids, 8);
                dbInnerTabulations = innerTabulationService.getRepository().getBiddingCompanyIdAndJieDuan(ids, 6);
            }
            if (ssdbInnerTabulations.size() > 0) {
                Map<Long, List<InnerTabulation>> idList = ssdbInnerTabulations.stream().collect(Collectors.groupingBy(vo -> vo.getBiddingCompany().getId()));
                ssdbInnerMark = idList.size();
                if (idList.size() == 1) {
                    ssdbSupplyCompany = ssdbInnerTabulations.get(0).getBiddingCompany().getSupplyCompany();
                }
            }
            if (dbInnerTabulations.size() > 0) {
                Map<Long, List<InnerTabulation>> idList = dbInnerTabulations.stream().collect(Collectors.groupingBy(vo -> vo.getBiddingCompany().getId()));
                dbInnerMark = idList.size();
                if (idList.size() == 1) {
                    dbSupplyCompany = dbInnerTabulations.get(0).getBiddingCompany().getSupplyCompany();
                }
            }
            List<InnerBidBaseTabulation> ssbdInnerBidBaseTabulations = innerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1, basisDemand.getProject().getId(), 2);
            List<InnerBidBaseTabulation> bdInnerBidBaseTabulations = innerBidBaseTabulationService.getRepository().findByFlagAndProjectIdAndBidType(1, basisDemand.getProject().getId(), 1);
            //返回最新的清单对应阶段
            SupplyCompany supplyCompany = null;
            if (ssdbInnerMark == 1) {
                jieDuan = 8;
                supplyCompany = ssdbSupplyCompany;
            } else if (ssbdInnerBidBaseTabulations.size() > 0) {
                jieDuan = 7;
            } else if (dbInnerMark == 1) {
                jieDuan = 6;
                supplyCompany = dbSupplyCompany;
            } else if (bdInnerBidBaseTabulations.size() > 0) {
                jieDuan = 1;
            }
            BasisDemandDetails demandDetails = basisDemandDetailsService.getRepository().findByFlagAndBasisDemandIdAndJieDuan(1, basisDemand.getId(), jieDuan);
            if (demandDetails == null) {
                demandDetails = new BasisDemandDetails();
                if (jieDuan != 0) {
                    demandDetails.setJieDuan(jieDuan);
                }
                demandDetails.setSupplyCompany(supplyCompany);
            }
            basisDemand.setDemandDetails(demandDetails);
        }

        Result result1 = new Result();
        result1.setData(list);
        result1.setCode(result.getCode());
        result1.setMessage(result.getMessage());
        result1.setPage(result.getPage());
        result1.setTotalElements(result.getTotalElements());
        result1.setTotalPage(result.getTotalPage());
        result1.setException(result.exception);
        return result1;
    }


}

